package work.vcloud.baseinfo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import work.vcloud.baseinfo.service.intfc.coursetable.BaseDataService;
import work.vcloud.baseinfo.utils.HttpUtil;
import work.vcloud.frame.controller.BaseController;
import work.vcloud.frame.dao.OpenDao;
import work.vcloud.frame.vo.OutputVo;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 课程表
 */
@RestController
@Scope("prototype")
public class CourseTableApiController extends BaseController {

    @Autowired
    OpenDao openDao;

    @Resource
    BaseDataService baseDataService;

    @Value("${courseTable.AdminLoginId}")
    String AdminLoginId;

    @Value("${courseTable.Key}")
    String Key;

    @Value("${courseTable.url}")
    String url;

    @Value("${courseTable.ScheduleList}")
    String ScheduleList;

    @Value("${courseTable.SourceDataPost}")
    String SourceDataPost;

    @Value("${courseTable.ScheduleGet}")
    String ScheduleGet;

    /**
     * 课表方案
     *
     * @return
     */
    @RequestMapping("courseTable/ScheduleList")
    public OutputVo ScheduleList() {
        try {
            Map<String, Object> map = getParameterMap();
            map.remove("page");

            Map<String, Object> sourceMap = new HashMap<>();
            sourceMap.put("AdminLoginId", AdminLoginId);
            sourceMap.put("Key", Key);

            String result = HttpUtil.doPost2(url + ScheduleList, (JSONObject) JSONObject.toJSON(sourceMap));
            System.out.println(result);
            JSONObject resultJsonObj = JSON.parseObject(result);
            JSONArray array = resultJsonObj.getJSONArray("Key");

            return output(array);
        } catch (Exception e) {
            e.printStackTrace();
            return output("9999");
        }
    }


    /**
     * 新建课表方案，并推送课表基础信息
     *
     * @return
     */
    @RequestMapping("courseTable/SourceDataPost")
    public OutputVo SourceDataPost() {
        try {
            Map<String, Object> map = getParameterMap();
            map.remove("page");

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = new Date();
            String timeStr = sdf.format(date);

            Map<String, Object> sourceMap = new HashMap<>();
            sourceMap.put("AdminLoginId", AdminLoginId);
            sourceMap.put("Key", Key);

            //课表方案
            Map<String, Object> schemaMap = new HashMap<>();
            sourceMap.put("Schema", schemaMap);
            /*schemaMap.put("TSJWID", "58a6fa4e-7c46-47a0-84d5-a82c679e9700");
            schemaMap.put("OtData", "58a6fa4e-7c46-47a0-84d5-a82c679e9700");*/

            schemaMap.put("Name", "课表方案" + timeStr);
            schemaMap.put("Remark", null);
            schemaMap.put("RecycleMode", "单周循环");

            boolean[] workdayArr = {false, true, true, true, true, true, false};
            schemaMap.put("WorkdayArr", workdayArr);

            Map userInfo = (Map) map.get("userInfo");
            map.put("fk_unit", userInfo.get("unitId"));
            //map.put("fk_stage", "9200f69c-700c-4c37-92c4-0200d466f4a1");

            //查询每天课时数量
            map.put("sqlMapId", "findCourseCountByDay");
            Map courseCountMap = (Map) openDao.queryForObject(map);
            int morningcount = Integer.parseInt(courseCountMap.get("morningcount").toString());
            int afternooncount = Integer.parseInt(courseCountMap.get("afternooncount").toString());

            int[] sectionSizeArr = {0, 0, morningcount, 0, afternooncount, 0};
            schemaMap.put("SectionSizeArr", sectionSizeArr);

            List baseDataList = new ArrayList();
            sourceMap.put("BaseDataList", baseDataList);

            //年级
            map.put("sqlMapId", "findGradeByUnit");
            List<Map<String, Object>> gradeList = openDao.queryForList(map);
            for (int i = 0; i < gradeList.size(); i++) {
                Map<String, Object> originGradeMap = gradeList.get(i);
                Map<String, Object> gradeMap = baseDataService.fillGrade(originGradeMap);
                baseDataList.add(gradeMap);
            }

            //班级
            map.put("sqlMapId", "findClassByUnit");
            List<Map<String, Object>> classList = openDao.queryForList(map);
            for (int i = 0; i < classList.size(); i++) {
                Map<String, Object> originClassMap = classList.get(i);
                Map<String, Object> classMap = baseDataService.fillClass(originClassMap);
                baseDataList.add(classMap);
            }

            //科目
            map.put("sqlMapId", "findCourse");
            List<Map<String, Object>> courseList = openDao.queryForList(map);
            for (int i = 0; i < courseList.size(); i++) {
                Map<String, Object> originCourseMap = courseList.get(i);
                Map<String, Object> courseMap = baseDataService.fillCourse(originCourseMap);
                baseDataList.add(courseMap);
            }

            //教师
            map.put("sqlMapId", "findTeacher");
            List<Map<String, Object>> teacherList = openDao.queryForList(map);
            for (int i = 0; i < teacherList.size(); i++) {
                Map<String, Object> originTeacherMap = teacherList.get(i);
                Map<String, Object> teacherMap = baseDataService.fillTeacher(originTeacherMap);
                baseDataList.add(teacherMap);
            }

            sourceMap.put("BaseDataRlnList", new ArrayList<>());
            sourceMap.put("BaseDataTimeRuleList", null);

            //任课信息
            List gradeLessonList = new ArrayList<>();
            sourceMap.put("GradeLessonList", gradeLessonList);
            //遍历年级和科目
            for (int i = 0; i < gradeList.size(); i++) {
                Map<String, Object> originGradeMap = gradeList.get(i);
                String fk_grade = (String) originGradeMap.get("id");
                String gradeName = (String) originGradeMap.get("name");
                map.put("fk_grade", fk_grade);
                for (int j = 0; j < courseList.size(); j++) {
                    Map<String, Object> originCourseMap = courseList.get(j);
                    String fk_course = (String) originCourseMap.get("id");
                    String courseName = (String) originCourseMap.get("name");
                    map.put("fk_course", fk_course);

                    //年级科目
                    Map<String, Object> gradeCourseMap = new HashMap<>();
                    gradeLessonList.add(gradeCourseMap);
                    gradeCourseMap.put("OtData", null);
                    gradeCourseMap.put("LessonCtry", null);

                    //年级
                    Map<String, Object> gradeMap = new HashMap<>();
                    gradeCourseMap.put("Grade", gradeMap);
                    gradeMap.put("Kind", "Grade");
                    gradeMap.put("ID", fk_grade);
                    gradeMap.put("Name", gradeName);

                    //科目
                    Map<String, Object> courseMap = new HashMap<>();
                    gradeCourseMap.put("Subject", courseMap);
                    courseMap.put("Kind", "Subject");
                    courseMap.put("ID", fk_course);
                    courseMap.put("Name", courseName);

                    //查询任课信息
                    map.put("sqlMapId", "findCourseInfo");
                    List<Map<String, Object>> courseInfoList = openDao.queryForList(map);

                    //每周上课节数
                    String actCombination = "1*5";
                    gradeCourseMap.put("GroupForBalance", "");

                    List itemList = new ArrayList();
                    gradeCourseMap.put("Items", itemList);

                    for (int k = 0; k < courseInfoList.size(); k++) {
                        Map<String, Object> originCourseInfoMap = courseInfoList.get(k);
                        Map<String, Object> itemMap = new HashMap<>();

                        itemMap.put("OtData", null);
                        itemMap.put("LessonCode", null);
                        itemMap.put("LessonCtry", null);
                        itemMap.put("Subject", courseMap);

                        String week = (String) originCourseInfoMap.get("week");
                        if (!StringUtils.isEmpty(week)) {
                            actCombination = "1*" + week;
                        }
                        itemMap.put("ActCombination", actCombination);
                        itemMap.put("GroupForBalance", "");
                        List memberList = new ArrayList();
                        itemMap.put("Members", memberList);

                        //班级
                        Map classMap = new HashMap();
                        classMap.put("Kind", "Squad");
                        classMap.put("ID", originCourseInfoMap.get("fk_class"));
                        classMap.put("Name", originCourseInfoMap.get("classname"));
                        memberList.add(classMap);

                        //教师
                        Map teacherMap = new HashMap();
                        teacherMap.put("Kind", "Teacher");
                        teacherMap.put("ID", originCourseInfoMap.get("fk_user"));
                        String idCard = (String) originCourseInfoMap.get("sfzjh");
                        teacherMap.put("Name", originCourseInfoMap.get("teachername") + "(" + idCard.substring(idCard.length() - 4, idCard.length()) + ")");
                        memberList.add(teacherMap);
                        itemList.add(itemMap);
                    }
                    gradeCourseMap.put("ActCombination", actCombination);
                }
            }

            System.out.println(JSONObject.toJSON(sourceMap).toString());

            String result = HttpUtil.doPost2(url + SourceDataPost, (JSONObject) JSONObject.toJSON(sourceMap));
            System.out.println(result);

            return output("0000");
        } catch (Exception e) {
            e.printStackTrace();
            return output("9999");
        }
    }

    /**
     * 获取课程表
     *
     * @return
     */
    @RequestMapping("courseTable/ScheduleGet")
    public OutputVo ScheduleGet() {
        try {
            Map<String, Object> map = getParameterMap();
            map.remove("page");

            Map userInfo = (Map) map.get("userInfo");
            map.put("fk_unit", userInfo.get("unitId"));
            //map.put("fk_unit", "8b690b86-1568-401b-b43e-bc4bf006fb23");
            //map.put("fk_stage", "9200f69c-700c-4c37-92c4-0200d466f4a1");

            //查询每天课时数量
            map.put("sqlMapId", "findCourseTime");
            map.put("timeSlot", "morning");
            List<Map<String, Object>> morningCourseTimeList = openDao.queryForList(map);
            map.put("timeSlot", "afternoon");
            List<Map<String, Object>> afternoonCourseTimeList = openDao.queryForList(map);
            map.remove("timeSlot");

            //查询任课信息
            map.put("sqlMapId", "findCourseInfo");
            List<Map<String, Object>> courseInfoList = openDao.queryForList(map);
            //任课信息映射（key：fk_course+","+fk_class+","+fk_user）
            Map<String, Map<String, Object>> courseInfoMapping = courseInfoList.stream().collect(Collectors.toMap(m -> m.get("fk_course") + "," + m.get("fk_class") + "," + m.get("fk_user"), m -> m));

            //查询课表方案所需数据
            Map sourceMap = new HashMap<String, Object>();
            sourceMap.put("AdminLoginId", AdminLoginId);
            sourceMap.put("Key", Key);
            sourceMap.put("TSJWID", map.get("TSJWID"));

            //课表方案信息
            String result = HttpUtil.doPost2(url + ScheduleGet, (JSONObject) JSONObject.toJSON(sourceMap));

            System.out.println(result);
            JSONObject resultJsonObj = JSON.parseObject(result);
            JSONObject keyObj = resultJsonObj.getJSONObject("Key");

            JSONArray baseDataList = keyObj.getJSONArray("BaseDataList");
            //年级
            List<JSONObject> gradeList = baseDataService.getGradeData(baseDataList);
            Map<String, JSONObject> gradeMapping = gradeList.stream().collect(Collectors.toMap(m -> m.get("ID").toString(), m -> m, (k1, k2) -> k1));

            //班级
            List<JSONObject> classList = baseDataService.getClassData(baseDataList);
            Map<String, JSONObject> classMapping = classList.stream().collect(Collectors.toMap(m -> m.get("ID").toString(), m -> m, (k1, k2) -> k1));

            //课程
            List<JSONObject> courseList = baseDataService.getCourseData(baseDataList);
            Map<String, JSONObject> courseMapping = courseList.stream().collect(Collectors.toMap(m -> m.get("ID").toString(), m -> m, (k1, k2) -> k1));

            //教师
            List<JSONObject> teacherList = baseDataService.getTeacherData(baseDataList);
            Map<String, JSONObject> teacherMapping = teacherList.stream().collect(Collectors.toMap(m -> m.get("ID").toString(), m -> m, (k1, k2) -> k1));


            List<Map<String, Object>> courseTableList = new ArrayList();
            JSONArray lessonCellList = keyObj.getJSONArray("LessonCellList");
            for (int i = 0; i < lessonCellList.size(); i++) {
                Map courseTableMap = new HashMap();
                courseTableList.add(courseTableMap);

                //课表信息
                JSONObject lessonCell = lessonCellList.getJSONObject(i);
                String courseTableId = lessonCell.getString("ID");
                courseTableMap.put("id", courseTableId);

                //科目
                JSONObject Subject = lessonCell.getJSONObject("Subject");
                String fk_course = courseMapping.get(Subject.getString("ID")).getString("OtData");
                String courseName = Subject.getString("Name");
                courseTableMap.put("courseName", courseName);

                //上课时间
                JSONObject Time = lessonCell.getJSONObject("Time");
                Integer Day = Time.getInteger("Day");
                Integer Section = Time.getInteger("Section");
                Integer SectionsOrder = Time.getInteger("SectionsOrder");
                //1: 单周， 2：双周， 3：每周，实际使用int
                Integer OddEven = Time.getInteger("OddEven");
                //周几
                courseTableMap.put("day", Day);
                //单双周
                courseTableMap.put("week", OddEven == 3 ? "0" : OddEven + "");

                //班级
                JSONArray Members_Squad = lessonCell.getJSONArray("Members_Squad");
                if (Members_Squad.size() <= 0) {
                    throw new Exception("班级不存在！");
                }
                JSONObject squad = Members_Squad.getJSONObject(0);
                String fk_class = classMapping.get(squad.getString("ID")).getString("OtData");
                String className = squad.getString("Name");
                courseTableMap.put("fk_class", fk_class);
                courseTableMap.put("className", className);

                //教师
                JSONArray Members_Teacher = lessonCell.getJSONArray("Members_Teacher");
                if (Members_Teacher.size() <= 0) {
                    throw new Exception("教师不存在！");
                }
                JSONObject teacher = Members_Teacher.getJSONObject(0);
                String fk_teacher = teacherMapping.get(teacher.getString("ID")).getString("OtData");
                courseTableMap.put("fk_teacher", fk_teacher);
                String teacherName = teacher.getString("Name");
                courseTableMap.put("teacherName", teacherName);

                //获取任课信息
                Map<String, Object> courseInfoMap = courseInfoMapping.get(fk_course + "," + fk_class + "," + fk_teacher);
                if (courseInfoMap == null) {
                    System.out.println(courseName + className + "没有排课数据！");
                    continue;
                }
                String fk_course_info = (String) courseInfoMap.get("id");
                courseTableMap.put("fk_course_info", fk_course_info);

                //任课时间
                if (Section == 2) {
                    Map<String, Object> courseTimeMap = morningCourseTimeList.get(SectionsOrder - 1);
                    String fk_course_time = (String) courseTimeMap.get("id");
                    courseTableMap.put("fk_course_time", fk_course_time);
                }
                if (Section == 4) {
                    Map<String, Object> courseTimeMap = afternoonCourseTimeList.get(SectionsOrder - 1);
                    String fk_course_time = (String) courseTimeMap.get("id");
                    courseTableMap.put("fk_course_time", fk_course_time);
                }
            }

            System.out.println(JSON.toJSONString(courseTableList));

            //删除课表数据
            map.put("sqlMapId", "deleteCourseTable");
            openDao.update(map);

            //添加课表数据
            for (int i = 0; i < courseTableList.size(); i++) {
                Map courseTableMap = courseTableList.get(i);
                map.putAll(courseTableMap);
                map.put("sqlMapId", "addCourseTable");
                openDao.insert(map);
            }
            return output("0000");
        } catch (Exception e) {
            e.printStackTrace();
            return output("9999");
        }
    }

}
